﻿using BlazorAdmin.Interface;
using BootstrapBlazor.Components;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlazorAdmin.Services.DbService
{
    /// <summary>
    /// 数据库服务基类
    /// </summary>
    public abstract class BaMgmtDbService
    {
        private readonly IPetaPoco dbManager;

        public BaMgmtDbService(IPetaPoco db)
        {
            dbManager = db;
        }

        protected IDatabase Create() => dbManager.Create();

        protected IDatabase Create(string connName) => dbManager.Create(connName);

        /// <summary>
        /// 插入实体数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public object Insert<T>(T data) where T : class
        {
            using IDatabase db = Create();
            var ret = db.Insert(data);

            db.LogAsync("Insert");

            return ret;
        }

        public async Task<object> InsertAsync<T>(T data) where T : class
        {
            using IDatabase db = Create();
            var ret = db.InsertAsync(data);

            db.LogAsync("Insert");

            return ret;
        }

        /// <summary>
        /// 获取数据集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public List<T> Fetch<T>()
        {
            using IDatabase db = Create();
            var ret = db.Fetch<T>();

            db.LogAsync("Fetch");

            return ret;
        }

        /// <summary>
        /// 获取数据集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql">查询语句</param>
        /// <param name="args"></param>
        /// <returns></returns>
        public List<T> Fetch<T>(string sql, params object[] args)
        {
            List<T> ret = null;

            try
            {
                using IDatabase db = Create();
                ret = db.Fetch<T>(sql, args);
            }
            catch (Exception ex)
            {

            }

            ///db.LogAsync("Fetch");

            return ret;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public T SingleOrDefault<T>(string sql, params object[] args)
        {
            using IDatabase db = Create();
            var ret = db.SingleOrDefault<T>(sql, args);

            db.LogAsync("SingleOrDefault");

            return ret;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public T FirstOrDefault<T>(string sql, params object[] args)
        {
            using IDatabase db = Create();
            var ret = db.FirstOrDefault<T>(sql, args);

            db.LogAsync("FirstOrDefault");

            return ret;
        }

        public int Update<T>(string sql, params object[] args)
        {
            using IDatabase db = Create();
            var ret = db.Update<T>(sql, args);

            db.LogAsync("Update");

            return ret;
        }

        /// <summary>
        /// 列表分页查询方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<QueryData<T>> PageQueryAsync<T>(AppQueryOption query)
        {
            var ret = new QueryData<T>()
            {
                IsSorted = true,
                IsFiltered = true,
                IsSearch = true,
                IsAdvanceSearch = query.Option.AdvanceSearchs.Any() || query.Option.CustomerSearchs.Any()
            };

            using var db = dbManager.Create();
            if (query.Option.IsPage)
            {
                Page<T> items;
                if (query.Sql != null)
                    items = await db.PageAsync<T>(query); //使用自定义查询
                else
                    items = await db.PageAsync<T>(query.Option); //未指定Sql，（单表查询）使用默认查询

                ret.TotalCount = Convert.ToInt32(items.TotalItems);
                ret.Items = items.Items;
            }
            else
            {
                List<T> items;
                if (query.Sql != null)
                    items = await db.FetchAsync<T>(query);
                else
                    items = await db.FetchAsync<T>(query.Option);

                ret.TotalCount = items.Count;
                ret.Items = items;
            }

            return ret;
        }
    }
}
